import type { AxiosResponse } from '@vben/request';

import { requestClient } from '#/api/request';

export interface TaskApplicationExportParams {
  name?: string;
  phone?: string;
  status?: string;
}

export interface TaskApplicationExportResult {
  blob: Blob;
  filename: string;
}

export interface TaskApplicationListParams extends TaskApplicationExportParams {
  page?: number;
  per_page?: number;
}

export interface TaskApplicationItem {
  id: string;
  name: string;
  phone: string;
  id_number: string;
  bank_card: string;
  status: string;
  status_label: string;
  sign_status?: string;
  contact_status?: string;
  created_at?: string;
}

export interface TaskApplicationListResponse {
  task: any;
  applications: {
    data: TaskApplicationItem[];
    current_page: number;
    per_page: number;
    total: number;
    last_page: number;
  };
}

const extractFilename = (contentDisposition?: string) => {
  if (!contentDisposition) {
    return '';
  }

  const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i);
  if (utf8Match?.[1]) {
    try {
      return decodeURIComponent(utf8Match[1]);
    } catch (error) {
      console.warn('文件名解码失败:', error);
    }
  }

  const fallbackMatch = contentDisposition.match(/filename="?([^";]+)"?/i);
  return fallbackMatch?.[1] ?? '';
};

const buildCleanParams = (params: TaskApplicationExportParams = {}) => {
  return Object.fromEntries(
    Object.entries(params).filter(([, value]) => value !== undefined && value !== ''),
  );
};

const downloadTaskApplicationExport = async (
  url: string,
  params: TaskApplicationExportParams = {},
  fallbackFilename: string,
): Promise<TaskApplicationExportResult> => {
  const response = await requestClient.download<AxiosResponse<Blob>>(url, {
    params: buildCleanParams(params),
    responseReturn: 'raw',
  });

  const disposition = response.headers?.['content-disposition'] ?? '';
  const filename = extractFilename(disposition) || fallbackFilename;

  return {
    blob: response.data,
    filename,
  };
};

export const exportTaskMemberListApi = async (
  taskId: string,
  params: TaskApplicationExportParams = {},
) =>
  downloadTaskApplicationExport(
    `/api/tenant/tasks/${taskId}/applications/export`,
    params,
    '成员列表.xlsx',
  );

export const exportTaskSettlementTemplateApi = async (
  taskId: string,
  params: TaskApplicationExportParams = {},
) =>
  downloadTaskApplicationExport(
    `/api/tenant/tasks/${taskId}/applications/export-settlement`,
    params,
    '结算模板.xlsx',
  );

export const getTaskApplicationsApi = async (
  taskId: string,
  params: TaskApplicationListParams = {},
) =>
  requestClient.get<TaskApplicationListResponse>(
    `/api/tenant/tasks/${taskId}/applications`,
    {
      params,
    },
  );

export const approveTaskApplicationApi = async (
  taskId: string,
  applicationId: string,
  payload: Record<string, unknown> = {},
) =>
  requestClient.post(`/api/tenant/tasks/${taskId}/applications/${applicationId}/approve`, payload);

export const rejectTaskApplicationApi = async (
  taskId: string,
  applicationId: string,
  data: { reason: string; notes?: string },
) =>
  requestClient.post(`/api/tenant/tasks/${taskId}/applications/${applicationId}/reject`, data);

export const dimissionTaskApplicationApi = async (
  taskId: string,
  applicationId: string,
  data: { notes?: string } = {},
) =>
  requestClient.post(`/api/tenant/tasks/${taskId}/applications/${applicationId}/dimission`, data);
